﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Xml.Serialization;

namespace Toybox.NicoSharp.Live
{
	using Extensions;
	using Primitives;
	using Utilities;

	/// <summary>
	/// PublishStatusクラス
	/// </summary>
	[XmlRoot("getpublishstatus")]
	public partial class PublishStatus : AbstractLiveStatus
	{

		#region [Static]

		/// <summary>
		/// PublishStatusの取得
		/// </summary>
		/// <param name="id"></param>
		/// <param name="cookies"></param>
		/// <returns></returns>
		public static PublishStatus Get(string completeId, CookieCollection cookies = null)
		{
			string url = NicoUrls.WatchLiveApi + "getpublishstatus/" + completeId;
			string xml = NicoWebClient.Get(url, cookies.Coerce());
			PublishStatus ps = Deserializer.XmlDeserializer<PublishStatus>(xml);
			ps.Cookies = cookies;
			return ps;
		}

		#endregion [Static]


		#region Public Members

		/// <summary>
		/// Stream情報
		/// </summary>
		public Stream stream;

		/// <summary>
		/// ユーザ情報
		/// </summary>
		public User user;

		/// <summary>
		/// RTMP情報
		/// </summary>
		public RTMP rtmp;

		#endregion Public Members

		#region Protected Members

		/// <summary>
		/// このクラス内で使うクッキー
		/// </summary>
		protected CookieCollection Cookies;

		#endregion Protected Members


		#region Public Methods

		/// <summary>
		/// 投稿者コメント送信
		/// </summary>
		/// <param name="command"></param>
		/// <param name="comment"></param>
		/// <param name="name"></param>
		/// <returns></returns>
		public bool PostOwnerChat(string body, string mail, string name = null)
		{
			if (string.IsNullOrEmpty(body))
				throw new ArgumentNullException("body");

			Dictionary<string, string> dict = new Dictionary<string, string>();
			dict.Add("body", Uri.EscapeUriString(body));
			dict.Add("mail", string.IsNullOrEmpty(mail) ? string.Empty : Uri.EscapeUriString(mail));

			if (!string.IsNullOrEmpty(name))
				dict.Add("name", name);

			dict.Add("is184", true.ToString());
			dict.Add("token", this.stream.token);

			string data = Serializer.AndEqualPairSerializer(dict);

			// コメント送信
			string url = NicoUrls.WatchLiveApi + "broadcast/" + this.stream.id;
			string html;
			try
			{
				html = NicoWebClient.Post(url, data, this.Cookies);
			}
			catch
			{
				return false;
			}

			foreach (var pair in Deserializer.AndEqualPairDeserializer(html))
			{
				if (pair.Key == "status" && pair.Value == "ok")
					return true;
			}
			return false;
		}

		#endregion Public Methods

	}
}